using System.Collections;
using System.Collections.Generic;

namespace Be.Timvw.Framework.Collections.Generic
{
    public static class EnumerableHelper
    {
        public static bool HaveSameElements<T>(IEnumerable<T> enumerable1, IEnumerable<T> enumerable2, Func<bool, T, T> areEqual)
        {
            IEnumerator<T> enumerator1 = enumerable1.GetEnumerator();
            IEnumerator<T> enumerator2 = enumerable2.GetEnumerator();

            while(enumerator1.MoveNext())
            {
                if(!enumerator2.MoveNext())
                {
                    return false;
                }

                if(!areEqual(enumerator1.Current, enumerator2.Current))
                {
                    return false;
                }
            }

            if(enumerator2.MoveNext())
            {
                return false;
            }

            return true;
        }

        public static bool HaveSameElements(IEnumerable enumerable1, IEnumerable enumerable2, Func<bool, object, object> areEqual)
        {
            IEnumerable<object> objectEnumerable1 = Convert<object>(enumerable1);
            IEnumerable<object> objectEnumerable2 = Convert<object>(enumerable2);
            return HaveSameElements(objectEnumerable1, objectEnumerable2, areEqual);
        }

        public static bool HaveSameElements(IEnumerable enumerable1, IEnumerable enumerable2)
        {
            return HaveSameElements(enumerable1, enumerable2, delegate(object t1, object t2) { return t1.Equals(t2); });
        }

        public static IEnumerable<TBase> Convert<TDerived, TBase>(IEnumerable<TDerived> enumerable) where TDerived : TBase
        {
            foreach(TDerived element in enumerable)
            {
                yield return element;
            }
        }

        public static IEnumerable<T> Convert<T>(IEnumerable enumerable)
        {
            foreach(T element in enumerable)
            {
                yield return element;
            }
        }
    }
}